<?php
declare (strict_types = 1);

namespace app\tools;

use app\exception\LogicException;
use Exception;
use Qcloud\Cos\Client;
use Qcloud\Cos\Exception\CosException;

final class CosTool
{
    private $bucket;
    private $region;
    private $secretId;
    private $secretKey;

    private $client;

    /**
     * CosTool constructor.
     * @throws LogicException
     */
    public function __construct()
    {
        $this->bucket = config('cos.bucket');
        $this->region = config('cos.region');
        $this->secretId = config('cos.secret_id');
        $this->secretKey = config('cos.secret_key');

        try {
            $this->client = new Client(
                [
                    'region' => $this->region,
                    'schema' => 'https', //协议头部，默认为http
                    'credentials'=> [
                        'secretId'  => $this->secretId,
                        'secretKey' => $this->secretKey
                    ]
                ]
            );
        } catch (CosException $e) {
            throw new LogicException($e->getMessage());
        }
    }

    /**
     * 简单上传--文件上传
     *
     * @param $object
     * @param $filePath
     * @return mixed
     * @throws LogicException
     */
    public function putObject($object, $filePath)
    {
        try {
            $this->client->putObject([
                'Bucket' => $this->bucket,
                'Key' => $object,
                'Body' => fopen($filePath, 'rb'),
            ]);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }

        return $object;
    }

    /**
     * 删除单个文件
     *
     * @param $object
     * @return bool
     * @throws LogicException
     */
    public function deleteObject($object)
    {
        try {
            $this->client->deleteObject([
                'Bucket' => $this->bucket,
                'Key' => $object
            ]);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }
        return true;
    }

    /**
     * 查询对象列表
     *
     * @return bool
     * @throws LogicException
     */
    public function listObjects()
    {
        try {
            $response =  $this->client->listObjects([
                'Bucket' => $this->bucket,
            ]);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }

        return $response->toArray();
    }
}
